import React from 'react';
import {
  ContextMenu,
  MenuItem,
  ContextMenuTrigger,
  connectMenu,
} from 'react-contextmenu';
import { isFunction } from '../../utils/is-object';
import './index.less';

const MENU_ID = 'menu_id';

function Menu(props) {
  const { id, trigger } = props;
  if (!trigger) {
    return null;
  }
  const { menus } = trigger;
  const onClick = (event, data) => {
    if (isFunction(data.action)) {
      data.action(trigger);
    }
  };

  return (
    <ContextMenu id={id}>
      {menus.map(menu => (
        <MenuItem
          key={menu.key} data={menu}
          onClick={onClick}
        >
          {menu.title}
        </MenuItem>
      ))}
    </ContextMenu>
  );
}

function MenuTrigger(props) {
  const collect = props => {
    return props;
  };
  const { node, editor, style, menus = [] } = props;
  return (
    <ContextMenuTrigger
      node={node}
      editor={editor}
      menus={menus}
      collect={collect}
      id={props.menuId || MENU_ID}
      attributes={{ style }}
    >
      {props.children}
    </ContextMenuTrigger>
  );
}

function getContextMenu(menuId) {
  return connectMenu(menuId || MENU_ID)(Menu);
}
export { MenuTrigger };
export { getContextMenu };
export default getContextMenu(MENU_ID);
